package com.example.app12_data_storage.activity;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.app12_data_storage.R;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 内部文件存储示例
 * @author lijiguo
 */
public class InnerFileActivity extends AppCompatActivity {

    private ImageView ivInnerFileLogo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_inner_file);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.ll_inner_file), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ivInnerFileLogo = findViewById(R.id.iv_inner_file_logo);
    }

    /**
     * 保存图片
     * @param view 发生点击事件的视图对象
     */
    public void save(View view) {
        // 获取AssetManager对象
        AssetManager assetManager = getAssets();
        String fileName = "avatar.png";
        // 获取文件输入流和输出流
        try(InputStream inputStream = assetManager.open(fileName);
            FileOutputStream outputStream = openFileOutput(fileName, Context.MODE_PRIVATE)) {

            byte[] buffer = new byte[1024];
            int len;
            while((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            // 提示消息
            Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取图片并显示
     * @param view 发生点击事件的视图对象
     */
    public void read(View view) {
        // 获取图片的路径
        String path = getFilesDir().getAbsolutePath();
        String fileName = "avatar.png";
        String filePath = path + "/" + fileName;
        // 加载图片文件得到bitmap对象
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        // 将图片显示在ImageView中
        ivInnerFileLogo.setImageBitmap(bitmap);
    }
}